import time
import random
from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.conf import settings
from wechatpy import WeChatPay

User = get_user_model()


# 微信支付配置
wechat_pay = WeChatPay(
    appid     = settings.WEPAY_APPID,
    api_key   = settings.WEPAY_API_KEY,
    mch_id    = settings.WEPAY_MCH_ID,
    mch_cert  = settings.WEPAY_MCH_CERT,
    mch_key   = settings.WEPAY_MCH_KEY,
)

def generate_out_trade_no():
    # 当前时间戳
    timestamp = int(time.time())
    # 生成一个1到9999之间的随机数
    random_num = random.randint(1, 9999)
    # 格式化订单号
    out_trade_no = f"{timestamp}{random_num:04d}"
    return out_trade_no




class Garage(models.Model):
    province = models.CharField(max_length=100, verbose_name="省份")
    address = models.CharField(max_length=255, verbose_name="地址")

    def __str__(self):
        return f"{self.province} - {self.address}"

    class Meta:
        verbose_name = "车库"
        verbose_name_plural = "车库管理"
   


################################################################################
#
# InGarageReport
#
################################################################################
# -------------------------------------------------------------------------------
# 	字段内容	字段类型	说明
# 1	甲方USERID	INT	
# 2	发起时间	Datetime	
# 3	车库名	Enum	后台创建的，选择列表
# 4	车牌号码	String	
# 5	车架号	String	
# 6	车型	String	
# 7	车辆类型	Enum	乘用车，商用车(<=9.6)，商用车(>=9.6)
# 8	车钥匙	Enum	有，无
# 9	送车人	String	
# 10	送车电话	String	
# 11	送车时间	Date	如：2024006-01
# 12	入库方式	Enum	就一个选项‘普通入库’
# 13	支付链接	String	费用>0 才显示
# 14	备注	Text	
# 15	回寄地址	String	
# 16	任务日期	Datetime	
# 17	完成日期	Datetime	
# 18	费用	Decimal	因为是入库报备，费用0.
# 19	完成反馈	?	带文字的多图（关联表）
# 20	管理员备注	Text	
# 21	记录状态	INT	整个服务记录流转情况，自定义
# 22	收费标准	INT	如：30元/天
# 23	钥匙	Enum	有，无
# 24	车门	Enum	开，关
# 25	行驶证	Enum	有，无
# 26	物品	Enum	有，无
# 27	损伤	Enum	有，无
# 28	封条	Enum	有，无
# -------------------------------------------------------------------------------
class InGarageReport(models.Model):
    VEHICLE_TYPE_CHOICES = [
        ('passenger', '乘用车'),
        ('commercial_lt_9_6', '商用车(<=9.6)'),
        ('commercial_gt_9_6', '商用车(>=9.6)')
    ]

    KEY_CHOICES = [('yes', '有'), ('no', '无')]
    DOOR_STATUS_CHOICES = [('open', '开'), ('close', '关')]
    STATUS_CHOICES = [(1, '待入库'), (2, '已取消'), (3, '已入库'), (4, '已拒绝')]

    # 甲方填写字段
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="甲方用户")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="发起时间")
    # garage_name = models.CharField(max_length=100, verbose_name="车库名")  # 使用 EnumField 需要预先定义选择项

    garage_name = models.ForeignKey(Garage, on_delete=models.CASCADE, verbose_name="车库名称")
    license_plate = models.CharField(max_length=20, verbose_name="车牌号码")
    vin = models.CharField(max_length=100, verbose_name="车架号")
    vehicle_model = models.CharField(max_length=100, verbose_name="车型")
    vehicle_type = models.CharField(max_length=50, choices=VEHICLE_TYPE_CHOICES, verbose_name="车辆类型")
    # has_key = models.CharField(max_length=3, choices=KEY_CHOICES, verbose_name="车钥匙")
    delivery_person = models.CharField(max_length=50, verbose_name="送车人")
    delivery_phone = models.CharField(max_length=15, verbose_name="送车电话")
    delivery_date = models.DateField(verbose_name="送车时间")
    storage_method = models.CharField(max_length=50, default='普通入库', verbose_name="入库方式")
    payment_link = models.URLField(blank=True, null=True, verbose_name="支付链接")
    remarks = models.TextField(blank=True, verbose_name="备注")
    return_address = models.CharField(max_length=200, verbose_name="回寄地址")

    # 乙方填写字段
    task_date = models.DateTimeField(blank=True, null=True, verbose_name="任务日期")
    completion_date = models.DateTimeField(blank=True, null=True, verbose_name="完成日期")
    cost = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="费用")
   
    status = models.IntegerField(choices=STATUS_CHOICES, default=1, verbose_name="记录状态")
    charge_standard = models.IntegerField(default=0, verbose_name="收费标准")

    has_key = models.CharField(blank=True, null=True, max_length=3, choices=KEY_CHOICES, verbose_name="钥匙")
    door_status = models.CharField(blank=True, null=True, max_length=5, choices=DOOR_STATUS_CHOICES, verbose_name="车门")
    has_license = models.CharField(blank=True, null=True, max_length=3, choices=KEY_CHOICES, verbose_name="行驶证")
    has_items = models.CharField(blank=True, null=True, max_length=3, choices=KEY_CHOICES, verbose_name="物品")
    has_damage = models.CharField(blank=True, null=True, max_length=3, choices=KEY_CHOICES, verbose_name="损伤")
    has_seal = models.CharField(blank=True, null=True, max_length=3, choices=KEY_CHOICES, verbose_name="封条")
    admin_remarks = models.TextField(blank=True, null=True, verbose_name="管理员备注")
    
    class Meta:
        verbose_name = "入库报备"
        verbose_name_plural = "入库报备"

    def __str__(self):
        return f"{self.license_plate} - {self.garage_name}"



class CompletionFeedback(models.Model):
    report = models.ForeignKey(InGarageReport, on_delete=models.CASCADE, related_name='feedbacks', verbose_name="报备记录")
    description = models.CharField(max_length=100, blank=True, null=True, verbose_name="反馈描述")
    images = models.ImageField(upload_to='feedback_images/', verbose_name="反馈图片")

    class Meta:
        verbose_name = "完成反馈"
        verbose_name_plural = "完成反馈"

    def __str__(self):
        return f"反馈 - {self.report.license_plate}"



################################################################################
#
# OutGarageReport
#
################################################################################
notes = """
5. 注意事项:
1) 请务必携带身份证原件，提车时间为 7：00-19：00, 其他时间提车需付200服务费
2) 严禁库管私自收取任何费用。如需支付手续费，请扫码提供的小区公告或扫码公司提供的收款码支付
3) 如后期更换提车人，请通知提车人带好委托书+原提车人身份证复印件+提车人身份证原件到场
"""

class OutGarageReport(models.Model):
    # 甲方用户输入字段
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="甲方用户")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="发起时间")
    client_name = models.CharField(max_length=100, verbose_name="甲方名")
    license_plate = models.CharField(max_length=20, verbose_name="车牌号")
    
    # 车内物品和停车费用的选项
    ITEM_CHOICES = [
        ('with_car', '随车'),
        ('in_storage', '留库'),
    ]
    FEE_CHOICES = [
        ('client', '甲方'),
        ('picker', '提车人'),
    ]
    item_status = models.CharField(max_length=20, choices=ITEM_CHOICES, verbose_name="车内物品")
    parking_fee_payer = models.CharField(max_length=20, choices=FEE_CHOICES, verbose_name="停车费用")

    picker_name = models.CharField(max_length=100, verbose_name="提车人")
    picker_id_number = models.CharField(max_length=18, verbose_name="身份证号码")
    picker_phone = models.CharField(max_length=15, verbose_name="提车人电话")
    pickup_date = models.DateField(verbose_name="提车时间")

    payment_link = models.URLField(blank=True, null=True, verbose_name="支付链接")
    
    # 出库方式固定为普通出库
    exit_method = models.CharField(max_length=20, default="普通出库", verbose_name="出库方式")
    remarks = models.TextField(blank=True, null=True,  verbose_name="备注")

    # 乙方用户输入字段
    task_date = models.DateTimeField(blank=True, null=True, verbose_name="任务日期")
    completion_date = models.DateTimeField(blank=True, null=True, verbose_name="完成日期")
    cost = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name="费用")  # 允许为空
    
    # 停放时长和支付状态
    parking_duration = models.IntegerField(blank=True, null=True, verbose_name="停放时长（天）")
    
    PAYMENT_STATUS_CHOICES = [
        ('unpaid', '未支付'),
        ('paid', '已支付'),
    ]
    payment_status = models.CharField(max_length=10, choices=PAYMENT_STATUS_CHOICES, verbose_name="支付状态")
    
    # 状态
    STATUS_CHOICES = [
        (1, '已提交'),
        (2, '已完成'),
    ]
    status = models.IntegerField(choices=STATUS_CHOICES, default=1, verbose_name="记录状态")
    admin_remarks = models.TextField(blank=True, null=True,  verbose_name="管理员备注")


    # 提车码和提车位置 for SMS
    pickup_service_phone = models.CharField(blank=True, null=True, max_length=15, default="027-86558888", verbose_name="总部电话")
    pickup_notes = models.CharField(blank=True, null=True, max_length=500, default=notes, verbose_name="注意事项")
    pickup_location = models.CharField(max_length=200, default='', verbose_name="提车位置")
    pickup_code = models.CharField(blank=True, null=True, max_length=16, default='', verbose_name="提车码")

    # def save(self, *args, **kwargs):
    #     if self.cost != None:
    #         if self.cost > 0 and not self.payment_link and self.status == 2:
    #             self.payment_link = self.generate_wechat_payment_link()
    #         super().save(*args, **kwargs)

    def generate_wechat_payment_link(self):
        # Implement the logic to generate a WeChat payment link
        # This is a placeholder implementation
        return f"https://wechatpay.com/pay?amount={self.cost}&id={self.id}"


        # # 生成商户订单号 -----------------------------------------------------------------------------
        # notify_url = 'https://www.yourserver.com/payments/notify'
        # order_data = {
        #     'body': "停车费用",                         # 暂时硬编码， 商品描述
        #     'out_trade_no': generate_out_trade_no(),   # 商户订单号# 暂时使用函数生成唯一的商户订单号
        #     'total_fee':    self.fee * 100,            # 订单总金额，单位为分
        #     'notify_url':   notify_url,                # 支付结果通知的URL
        #     'trade_type':   'MWEB',                    # 交易类型，MWEB为H5支付
        # }
        # prepay_id = wechat_pay.order.create(**order_data)
        # payment_link = wechat_pay.order.get_pay_url(prepay_id)
        # return payment_link

    

    class Meta:
        verbose_name = "出库报备"
        verbose_name_plural = "出库报备"

    def __str__(self):
        return f"{self.license_plate} - {self.client_name}"

class OgrCompletionFeedback(models.Model):
    report = models.ForeignKey(OutGarageReport, on_delete=models.CASCADE, related_name='feedbacks', verbose_name="报备记录")
    description = models.CharField(max_length=100, blank=True, null=True, verbose_name="反馈描述")
    images = models.ImageField(upload_to='completion_feedback_images/', verbose_name="反馈图片")

    class Meta:
        verbose_name = "完成反馈"
        verbose_name_plural = "完成反馈"

    def __str__(self):
        return f"反馈 - {self.report.license_plate}"


################################################################################
#
# VehicleMaintenance
#
################################################################################

class VehicleMaintenance(models.Model):
    # 甲方用户填写的字段
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="甲方用户")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="发起时间")
    client_name = models.CharField(max_length=100, verbose_name="甲方名")
    license_plate = models.CharField(max_length=20, verbose_name="车牌号码")
    maintenance_content = models.TextField(verbose_name="维修内容")
    
    # 支付方式和支付链接
    PAYMENT_METHOD_CHOICES = [
        ('client', '甲方'),
        ('picker', '提车人'),
    ]
    payment_method = models.CharField(max_length=10, choices=PAYMENT_METHOD_CHOICES, verbose_name="支付方式")
    payment_link = models.URLField(blank=True, null=True, verbose_name="支付链接")
    remarks = models.TextField(blank=True, verbose_name="备注")

    # 乙方用户填写的字段
    maintenance_date = models.DateTimeField(blank=True, null=True, verbose_name="维修日期")
    completion_date = models.DateTimeField(blank=True, null=True, verbose_name="完成日期")
    cost = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="费用")
    
    # 状态和支付状态
    STATUS_CHOICES = [
        (1, '已提交'),
        (2, '已完成'),
    ]
    status = models.IntegerField(choices=STATUS_CHOICES, default=1, verbose_name="记录状态")

    PAYMENT_STATUS_CHOICES = [
        ('unpaid', '未支付'),
        ('paid', '已支付'),
    ]
    payment_status = models.CharField(max_length=10, choices=PAYMENT_STATUS_CHOICES, verbose_name="支付状态")
    admin_remarks = models.TextField(blank=True, verbose_name="管理员备注")

    class Meta:
        verbose_name = "车辆维修"
        verbose_name_plural = "车辆维修"

    def __str__(self):
        return f"{self.license_plate} - {self.client_name}"

class VmCompletionFeedback(models.Model):
    report = models.ForeignKey(VehicleMaintenance, on_delete=models.CASCADE, related_name='feedbacks', verbose_name="维修记录")
    description = models.CharField(max_length=100, blank=True, null=True, verbose_name="反馈描述")
    images = models.ImageField(upload_to='completion_feedback_images/', verbose_name="反馈图片")

    class Meta:
        verbose_name = "完成反馈"
        verbose_name_plural = "完成反馈"

    def __str__(self):
        return f"反馈 - {self.report.license_plate}"



################################################################################
#
# ItemSentback
#
################################################################################

class ItemSentback(models.Model):
    # 甲方用户填写的字段
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="甲方用户")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="发起时间")
    client_name = models.CharField(max_length=100, verbose_name="甲方名")
    license_plate = models.CharField(max_length=20, verbose_name="车牌号码")
    payment_link = models.URLField(blank=True, null=True, verbose_name="支付链接")
    remarks = models.TextField(blank=True, verbose_name="备注")
    tracking_number = models.CharField(max_length=100, verbose_name="物流单号")

    # 乙方管理员填写的字段
    service_date = models.DateTimeField(blank=True, null=True, verbose_name="服务日期")
    completion_date = models.DateTimeField(blank=True, null=True, verbose_name="完成日期")
    cost = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="费用")
    
    # 状态字段
    STATUS_CHOICES = [
        (1, '已提交'),
        (2, '已完成'),
    ]
    status = models.IntegerField(choices=STATUS_CHOICES, default=1, verbose_name="记录状态")

    # 支付状态
    PAYMENT_STATUS_CHOICES = [
        ('unpaid', '未支付'),
        ('paid', '已支付'),
    ]
    payment_status = models.CharField(max_length=10, choices=PAYMENT_STATUS_CHOICES, verbose_name="支付状态")
    admin_remarks = models.TextField(blank=True, verbose_name="管理员备注")

    class Meta:
        verbose_name = "物品寄回"
        verbose_name_plural = "物品寄回"

    def __str__(self):
        return f"{self.license_plate} - {self.client_name}"

class IsbCompletionFeedback(models.Model):
    report = models.ForeignKey(ItemSentback, on_delete=models.CASCADE, related_name='feedbacks', verbose_name="物品寄回记录")
    description = models.CharField(max_length=100, blank=True, null=True, verbose_name="反馈描述")
    images = models.ImageField(upload_to='completion_feedback_images/', verbose_name="反馈图片")

    class Meta:
        verbose_name = "完成反馈"
        verbose_name_plural = "完成反馈"

    def __str__(self):
        return f"反馈 - {self.report.license_plate}"



################################################################################
#
# KeyDuplication
#
################################################################################

class KeyDuplication(models.Model):
    # 甲方用户填写的字段
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="甲方用户")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="发起时间")
    client_name = models.CharField(max_length=100, verbose_name="甲方名")
    license_plate = models.CharField(max_length=20, verbose_name="车牌号码")
    task_description = models.TextField(verbose_name="任务说明")
    
    PAYMENT_METHOD_CHOICES = [
        ('client', '甲方'),
        ('picker', '提车人'),
    ]
    payment_method = models.CharField(max_length=10, choices=PAYMENT_METHOD_CHOICES, verbose_name="支付方式")
    payment_link = models.URLField(blank=True, null=True, verbose_name="支付链接")
    remarks = models.TextField(blank=True, verbose_name="备注")

    RETURN_ITEMS_CHOICES = [
        ('yes', '是'),
        ('no', '否'),
    ]
    return_items = models.CharField(max_length=10, choices=RETURN_ITEMS_CHOICES, verbose_name="物品回寄")
    return_address = models.CharField(max_length=255, verbose_name="回寄地址")

    # 乙方用户填写的字段
    task_date = models.DateTimeField(blank=True, null=True, verbose_name="任务日期")
    completion_date = models.DateTimeField(blank=True, null=True, verbose_name="完成日期")
    cost = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="费用")

    STATUS_CHOICES = [
        (1, '已提交'),
        (2, '已完成'),
    ]
    status = models.IntegerField(choices=STATUS_CHOICES, default=1, verbose_name="记录状态")

    PAYMENT_STATUS_CHOICES = [
        ('unpaid', '未支付'),
        ('paid', '已支付'),
    ]
    payment_status = models.CharField(max_length=10, choices=PAYMENT_STATUS_CHOICES, verbose_name="支付状态")
    admin_remarks = models.TextField(blank=True, verbose_name="管理员备注")
    class Meta:
        verbose_name = "配钥匙"
        verbose_name_plural = "配钥匙"

    def __str__(self):
        return f"{self.license_plate} - {self.client_name}"

class KdCompletionFeedback(models.Model):
    report = models.ForeignKey(KeyDuplication, on_delete=models.CASCADE, related_name='feedbacks', verbose_name="配钥匙记录")
    description = models.CharField(max_length=100, blank=True, null=True, verbose_name="反馈描述")
    images = models.ImageField(upload_to='completion_feedback_images/', verbose_name="反馈图片")

    class Meta:
        verbose_name = "完成反馈"
        verbose_name_plural = "完成反馈"

    def __str__(self):
        return f"反馈 - {self.report.license_plate}"




################################################################################
#
# MailKey
#
################################################################################

class MailKey(models.Model):
    # 甲方用户填写的字段
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="甲方用户")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="发起时间")
    client_name = models.CharField(max_length=100, verbose_name="甲方名")
    license_plate = models.CharField(max_length=20, verbose_name="车牌号码")
    task_description = models.TextField(verbose_name="任务说明")
    tracking_number = models.CharField(max_length=100, verbose_name="物流单号")
    payment_link = models.URLField(blank=True, null=True, verbose_name="支付链接")
    remarks = models.TextField(blank=True, verbose_name="备注")

    RETURN_ITEMS_CHOICES = [
        ('yes', '是'),
        ('no', '否'),
    ]
    return_items = models.CharField(max_length=10, choices=RETURN_ITEMS_CHOICES, verbose_name="物品回寄")
    return_address = models.CharField(max_length=255, verbose_name="回寄地址")

    # 乙方用户填写的字段
    task_date = models.DateTimeField(blank=True, null=True, verbose_name="任务日期")
    completion_date = models.DateTimeField(blank=True, null=True, verbose_name="完成日期")
    cost = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="费用")

    STATUS_CHOICES = [
        (1, '已提交'),
        (2, '已完成'),
    ]
    status = models.IntegerField(choices=STATUS_CHOICES, default=1, verbose_name="记录状态")

    PAYMENT_STATUS_CHOICES = [
        ('unpaid', '未支付'),
        ('paid', '已支付'),
    ]
    payment_status = models.CharField(max_length=10, choices=PAYMENT_STATUS_CHOICES, verbose_name="支付状态")
    admin_remarks = models.TextField(blank=True, verbose_name="管理员备注")

    class Meta:
        verbose_name = "寄钥匙"
        verbose_name_plural = "寄钥匙"

    def __str__(self):
        return f"{self.license_plate} - {self.client_name}"

class MkCompletionFeedback(models.Model):
    report = models.ForeignKey(MailKey, on_delete=models.CASCADE, related_name='feedbacks', verbose_name="寄钥匙记录")
    description = models.CharField(max_length=100, blank=True, null=True, verbose_name="反馈描述")
    images = models.ImageField(upload_to='completion_feedback_images/', verbose_name="反馈图片")

    class Meta:
        verbose_name = "完成反馈"
        verbose_name_plural = "完成反馈"

    def __str__(self):
        return f"反馈 - {self.report.license_plate}"


